<?php
Abstract class PdoModel{

    const UPLOAD_IMAGE_PATH = '/attach/img/';
    const UPLOAD_AVATAR_PATH = '/attach/avatar/';
    const UPLOAD_QRCODE_PATH = '/attach/qrcode/';
    const UPLOAD_GAOE_PATH = '/attach/gaoe/';
    const HTTP_TIME_OUT = 5; #curl超时时间


    public $pdo = null;
    protected $_name = '';

    public function __construct()
    {
        $mysql_config = Yaf_Registry::get("config")->get('product.mysql');


        $this->pdo = "mysql:host=localhost;dbname=testwhere";
        $this->pdo = new PDO($this->pdo, 'root', 'Sem_1653');
        $this->pdo->query('set names utf8;');

//        $this->pdo = "mysql:host=rm-uf62p4997i0tgn546.mysql.rds.aliyuncs.com;dbname=touhao";
//        $this->pdo = new PDO($this->pdo, 'thsw', 'Wl0129_best');
//        $this->pdo->query('set names utf8;');
    }

    /**
     * Insert 插入
     * @param $data
     * @return Int
     */
    public function insert($data)
    {
        if(empty($data)){
            return false;
        }
        $strSql = "INSERT INTO `$this->_name` (`".implode('`,`', array_keys($data))."`) VALUES ('".implode("','", $data)."')";
        $this->execSql($strSql);
        return $this->pdo->lastInsertId();
    }

    /**
     * Delete 删除
     * @param $where
     * @return Int
     */
    public function delete($where)
    {
        if(empty($where)){
            return false;
        }
        $strSql = "DELETE FROM `$this->_name` WHERE $where";
        return $this->execSql($strSql);
    }

    /**
     * Insert 更新
     * @param $data
     * @param $where
     * @return Int
     */
    function update($data,$where){
        if(empty($data) || empty($where)){
            return false;
        }
        $strSql = '';
        foreach ($data as $key => $value) {
            $strSql .= ", `$key`='$value'";
        }
        $strSql = substr($strSql, 1);
        $strSql = "UPDATE `$this->_name` SET $strSql WHERE $where";

        return $this->execSql($strSql);
    }


    /**
     * Select 查一条数据
     * @param $where
     * @return array
     */
    function find($where){
        if(empty($where)){
            return false;
        }
        return $this->pdo->query("SELECT * FROM `$this->_name` WHERE ". $where ." limit 1")->fetch(PDO::FETCH_ASSOC);
    }

    /**
     * Select 查一条
     * @param $sql
     * @return array
     */
    function fetchRow($sql){
        if(empty($sql)){
            return false;
        }
        return $this->pdo->query($sql)->fetch(PDO::FETCH_ASSOC);
    }

    /**
     * Select 查所有
     * @param $sql
     * @return array
     */
    function fetchAll($sql){
        if(empty($sql)){
            return false;
        }
        return $this->pdo->query($sql)->fetchAll(PDO::FETCH_ASSOC);
    }

    /**
     * exec 执行
     * @param $sql
     * @return array
     */
    function execSql($sql){
        if(empty($sql)){
            return false;
        }
        return $this->pdo->exec($sql);
    }

    /**
     * beginTransaction 事务开始
     */
    public function beginTransaction()
    {
        $this->pdo->beginTransaction();
    }

    /**
     * commit 事务提交
     */
    public function commit()
    {
        $this->pdo->commit();
    }

    /**
     * rollback 事务回滚
     */
    public function rollback()
    {
        $this->pdo->rollback();
    }

    /**
     * prepare 预处理
     * @param $sql
     * @return object
     */
    public function prepareSql($sql){
        return $this->pdo->prepare($sql);
    }

    /**
     * execute 执行预处理
     * @param $presql
     * @return object
     */
    public function execute($presql){
        return $this->pdo->execute($presql);
    }


    /**
     * transaction 通过事务处理多条SQL语句
     * @param array $arraySql
     * @return Boolean
     */
    public function execTransaction($arraySql)
    {
        $result = true;
        $this->beginTransaction();
        foreach ($arraySql as $strSql) {
            if ($this->execSql($strSql) == 0){
                $result = false;
            }
        }
        if ($result) {
            $this->commit();
        } else {
            $this->rollback();
        }
        return $result;
    }


    /**
     * getPDOError 捕获PDO错误信息
     */
    private function getPDOError()
    {
        if ($this->pdo->errorCode() != '00000') {
            $arrayError = $this->pdo->errorInfo();
            throw new Exception('MySQL Error:'.$arrayError[2]);
        }
    }


    public function addPic($upload_file = 'upload_file', $remote_pic = '')
    {
        if(empty($remote_pic)){
            $ext_name = substr(strrchr($_FILES[$upload_file]['name'], '.'), 1);
            $remote_pic = time() . rand(1000, 9999) . '.' . $ext_name;
        }
        return $this->uploadQiniu($upload_file, $remote_pic);
    }

    #图片上传到七牛
    public function uploadQiniu($upload_file = 'upload_file', $remote_pic = ''){

        if(isset($_FILES[$upload_file]) && $_FILES[$upload_file]['error'] == 0 ){
            $ext_name = substr(strrchr($_FILES[$upload_file]['name'],'.'),1);
            try{
                $cloud_obj = new CloudFileSystem();
                if(empty($remote_pic)) {
                    $remote_pic = uniqid(rand(), true).".".$ext_name;
                }
                if(isset($_FILES[$upload_file])){
                    $flag = $cloud_obj->upload($upload_file,$remote_pic);
                    if($flag) {
                        return $remote_pic;
                    } else {
                        return false;
                    }
                }
            }catch(Exception $ex){
                $this->logException($ex->getMessage());
                return false;
            }
        }else{
            return "";
        }
    }


    /**
     * 上传到本地
     * @param $rangle :图片旋转，负数逆时针，正数顺时针
     */
    function uploadLocal($upload_field = '', $newanme = '', $rotate_flag = 0, $gen_clear = 0, $newwidth = 400, $newheight=400, $rangle = 0){

        $newpath = APPLICATION_PATH.$newanme;
        $this->mkdirs(dirname($newpath));
        $tmp_name = $_FILES[$upload_field]['tmp_name'];

        $attach_saved = false;
        if(@copy($tmp_name, $newpath) || (function_exists('move_uploaded_file') && @move_uploaded_file($tmp_name, $newpath)) || @rename($tmp_name, $newpath)) {
            @unlink($tmp_name);
            $attach_saved = true;
        }
        if(!$attach_saved && is_readable($tmp_name)) {
            $fp = @fopen($tmp_name, 'rb');
            @flock($fp, 2);
            $attachedfile = @fread($fp, $_FILES[$upload_field]['size']);
            @fclose($fp);

            $fp = @fopen($newpath, 'wb');
            @flock($fp, 2);
            if(@fwrite($fp, $attachedfile)) {
                @unlink($tmp_name);
                $attach_saved = true;
            }
            @fclose($fp);
        }
        if(!$attach_saved) {
            return false;
        } else {
            if($gen_clear) {
                $this->genClearImage($newpath, $newpath, $newwidth, $newheight, $rangle);
            }
            return true;
        }
    }


    #处理图片精度和大小
    function genClearImage($newpath, $outpath, $newWidth=400, $newHeight=400, $rotate_rangle=0) {
        $originUrl = $newpath;
        $destUrl = $outpath;
        if (false !== $pos = strrpos($originUrl, ".")) {
            $originType = substr($originUrl, $pos + 1);
        }
        if ("gif" == strtolower ($originType)) {
            $originImg = imagecreatefromgif($originUrl);
        } else if ("jpg" == strtolower ($originType) || "jpeg" == strtolower ($originType)) {
            $originImg = imagecreatefromjpeg($originUrl);
        } else if ("png" == strtolower ($originType)) {
            $originImg = imagecreatefrompng($originUrl);
        } else {
            return true;
        }
        if(!empty($rotate_rangle)) {
            $originImg = imagerotate($originImg, $rotate_rangle, 0);
        }
        $originX = imagesx($originImg);
        $originY = imagesy($originImg);
        if (0 == $newWidth || 0 > $newWidth || $originX < $newWidth) {
            $newWidth = $originX;
        }
        if (0 == $newHeight || 0 > $newHeight || $originY < $newHeight) {
            $newHeight = $originY;
        }
        $scaleX = $originX / $newWidth;
        $scaleY = $originY / $newHeight;
        $scale = $scaleX > $scaleY ? $scaleX : $scaleY;
        $destImg = imagecreatetruecolor($originX / $scale, $originY / $scale);
        imagecopyresampled($destImg, $originImg, 0, 0, 0, 0, $originX / $scale, $originY / $scale, $originX, $originY);
        if (false !== $pos = strrpos($destUrl, ".")) {
            $destType = substr($destUrl, $pos + 1);
        }
        if ("gif" == strtolower ($destType)) {
            imagegif($destImg, $destUrl);
        } else if ("jpg" == strtolower ($destType) || "jpeg" == strtolower ($destType)) {
            imagejpeg($destImg, $destUrl);
        } else if ("png" == strtolower ($destType)) {
            imagepng($destImg, $destUrl);
        } else {
            return false;
        }
        return true;
    }

    #服务器本地图片上传到七牛
    public function uploadLocalFileToQiniu($file_path, $remote_pic = ''){

        $cloud_obj = new CloudFileSystem();
        if(empty($remote_pic)) {
            $ext_name = substr(strrchr($file_path,'.'),1);
            $remote_pic = uniqid(rand(), true).".".$ext_name;
        }
        $flag = $cloud_obj->delete($remote_pic);
        $flag = $cloud_obj->upload_from_localfile($file_path, $remote_pic);
        return $flag ? $remote_pic : false;
    }


    #抓取远程图片,存到服务器
    function GetRemotePic($url, $filename, $type = 1){
        if(trim($url)==''){
            return false;
        }
        $newpath = APPLICATION_PATH.$filename;

        $this->mkdirs(dirname($newpath));

        #两种办法去抓去数据
        if($type){
            $ch = curl_init();
            $timeout = 10;
            curl_setopt($ch,CURLOPT_URL, $url);
            curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch,CURLOPT_CONNECTTIMEOUT, $timeout);
            $file = curl_exec($ch);
            curl_close($ch);
        }else{
            ob_start();
            readfile($url);
            $file = ob_get_contents();
            ob_end_clean();
        }

        //文件大小
        $fp2 = fopen($newpath, 'a');
        fwrite($fp2, $file);
        fclose($fp2);
        unset($file, $url);
        return true;
    }


    function mkdirs($dir) {
        if(!is_dir($dir)) {
            if(!$this->mkdirs(dirname($dir))) {
                return false;
            }
            if(!mkdir($dir, 0777)){
                return false;
            }
        }
        return true;
    }


    #获取当前访问IP
    function getIp(){
        if (getenv('HTTP_CLIENT_IP')) {
            $now_ip = getenv('HTTP_CLIENT_IP');
        } elseif (getenv('HTTP_FORWARDED_FOR')) {
            $now_ip = getenv('HTTP_FORWARDED_FOR');
        } elseif (getenv('HTTP_X_FORWARDED')) {
            $now_ip = getenv('HTTP_X_FORWARDED');
        } elseif (getenv('HTTP_FORWARDED')) {
            $now_ip = getenv('HTTP_FORWARDED');
        } elseif (getenv('HTTP_X_FORWARDED_FOR')) {
            $now_ip = getenv('HTTP_X_FORWARDED_FOR');
        } else {
            $now_ip = $_SERVER['REMOTE_ADDR'];
        }
        return $now_ip;
    }


    /**
     * 获取远程URL回调
     * @param $statusCode : 响应的状态码
     * @param $timeout : 请求超时时间
     */
    public function GetRemoteURL($url = '', &$statusCode = 200, $timeout = 0, $header = array()){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, (empty($timeout) ? SELF::HTTP_TIME_OUT : $timeout));
        curl_setopt($ch, CURLOPT_HEADER, 0);
        if(!empty($header)){
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        }

        $output = curl_exec($ch);
        $statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        return $output;
    }

    public function FileGetContents($url = ''){
        return file_get_contents($url);
    }


    function _multi_array_sort($multi_array, $sort_key, $sort=SORT_ASC){
        $key_array = array();
        if(!empty($multi_array) && is_array($multi_array)){
            foreach ($multi_array as $row_array){
                if(is_array($row_array)){
                    $key_array[] = $row_array[$sort_key];
                }else{
                    return array();
                }
            }
        } else {
            return array();
        }
        array_multisort($key_array, $sort, SORT_NUMERIC, $multi_array);
        return $multi_array;
    }

    function post_curl($url,$data){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        $result_json = curl_exec($ch);
        curl_close($ch);
        return  json_decode($result_json, true);
    }


}
